<?php declare(strict_types=1);
/**
 * This file is part of Swoft.
 *
 * @link https://swoft.org
 * @document https://swoft.org/docs
 * @contact group@swoft.org
 * @license https://github.com/swoft-cloud/swoft/blob/master/LICENSE
 */

namespace App\Http\Middleware;

use App\Exception\HttpExecption;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\RequestHandlerInterface;
use Swoft\Bean\Annotation\Mapping\Bean;
use Swoft\Http\Message\Request;
use Swoft\Http\Server\Contract\MiddlewareInterface;
use Swoft\Http\Session\HttpSession;
use function context;

/**
 * Class CheckLoginMiddleware - Custom middleware
 * @Bean()
 * @package App\Http\Middleware
 */
class CheckLoginMiddleware implements MiddlewareInterface
{
    /**
     * Process an incoming server request.
     *
     * @param ServerRequestInterface|Request $request
     * @param RequestHandlerInterface $handler
     *
     * @return ResponseInterface
     * @throws HttpExecption
     * @inheritdoc
     */
    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
    {
        if(HttpSession::current()->has("username") && HttpSession::current()->has("userid")){
            // before request handle
            return $handler->handle($request);
        }
        //判断请求类型
        if($request->isAjax()){
            throw new HttpExecption("登录超时",3);
        }
        return context()->getResponse()->redirect("/admin/login");

        // after request handle
    }
}
